//
//  BlueToothDataHandle.m
//  JunZeWristband
//
//  Created by Kendama on 2017/9/19.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "BlueToothDataHandle.h"
#import "NSString+FIDExtra.h"
#import "SportModel.h"
#import "SportHistoryModel.h"
#import "UploadSportDataApi.h"
#import "SetTodayRadiationApi.h"
#import "SleepModel.h"
#import "SleepHistoryModel.h"
#import "UploadSleepDataApi.h"

@interface BlueToothDataHandle()
/** <#Description#> **/
@property(nonatomic,strong) NSMutableArray *sportArray;
@property(nonatomic,strong) NSMutableArray *sleepArray;

@end

@implementation BlueToothDataHandle


typedef NS_ENUM(NSInteger, BackCode) {
    //设置日期/时间/星期
    Time = 0,
    //获取（历史）步数/里程/卡路里
    Step = 3,
    //步数/里程/卡路里清零
    Clear = 4,
    //用户信息推送(可选)
//    UserInfoPush = 6,
    //来电/短信(邮件)/消息推送
    Push = 8,
    //获取睡眠数据 0c
    Sleep = 12,
    
    //设备电池电量报告
    Battery = 15,
    
    // 幅射
    Radiate = 32
    
};

+ (BlueToothDataHandle *)sharedInstance{
    
    
    static BlueToothDataHandle *static_manager = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        static_manager = [[BlueToothDataHandle alloc]init];
        static_manager.deviceInfoModel = [[DeviceInfoModel alloc] init];
        static_manager.radiateMax = 0;
    });
    
    return static_manager;
}


- (void)notifyBlueToothWireteDataBack:(NSData *)data sendeByDevice:(DTCDeviceModel *)deviceModel{
    
    NSString *dataString = [NSString convertDataToHexStr:data].uppercaseString;
    if ([EXRACT_OBJECT(MAC) isEqualToString:deviceModel.mac])
    {
        if (dataString.length == 40)
        {
            NSString *code = dataString.toIndex(2);
            switch ([[NSString hexadecimalToDecimal:code] intValue]) {
                case Step:
                {
                    [self handleSportData:dataString];
                }
                    break;
                case Battery:
                {
                    [self handleBattery:dataString];
                }
                    break;
                case Radiate:
                {
                    [self handleRadiate:dataString];
                }
                    break;
                case Sleep:
                {
                    [self hanleSleep:dataString];
                }
                    break;
                default:
                    break;
            }
        }
    }


}


#pragma mark ---- 睡眠值处理 ------
- (void)hanleSleep:(NSString *)dataString
{
    NSString *code = dataString.subString(2,4); // OP
    switch ([code intValue]) {
        case 0: //最近一次睡眠数据
        {
            SleepModel *sleepModel = [[SleepModel alloc] initWithHexadecimalBackContent:dataString.subString(28,36) propertyBytes:@[@"2",@"2",@"2",@"2"]];
//            NSString *deepSleep = [NSString stringWithFormat:@"%i",([[NSString hexadecimalToDecimal:sleepModel.Dh] intValue]<<8)+[sleepModel.D1 intValue]];
//            NSString *lightSleep = [NSString stringWithFormat:@"%i",([[NSString hexadecimalToDecimal:sleepModel.Lh] intValue]<<8)+[sleepModel.L1 intValue]];
            NSString *deepSleep = [self handleSleepDataWithDh:sleepModel.Dh D1:sleepModel.D1];
            NSString *lightSleep = [self handleSleepDataWithDh:sleepModel.Lh D1:sleepModel.L1];
            if (self.sleepBlock)
            {
                self.sleepBlock(deepSleep, lightSleep);
            }
        }
            break;
        case 1: //历史睡眠数据
        {
            [self handleSleepHistory:dataString];
        }
            break;
        case 2: //历史数据条数
        {
            
        }
            break;
            
        default:
            break;
    }
}

- (NSString *)handleSleepDataWithDh:(NSString *)Dh D1:(NSString *)D1
{
    NSLog(@"睡眠%@",[NSString hexadecimalToDecimal:D1]);
    return  [NSString stringWithFormat:@"%i",(int)([[NSString hexadecimalToDecimal:Dh] intValue]<<8)+[[NSString hexadecimalToDecimal:D1] intValue]];
}

- (void)handleSleepHistory:(NSString *)dataString
{
    NSInteger count = [[NSString hexadecimalToDecimal:dataString.subString(4,6)] intValue];//总数
    
    if (count > 0)
    {
        SleepHistoryModel *sleepHistoryModel = [[SleepHistoryModel alloc] initWithHexadecimalBackContent:dataString.subString(8,36) propertyBytes:@[@"6",@"2",@"2",@"6",@"2",@"2",@"2",@"2",@"2",@"2"]];
        [self.sleepArray addObject:sleepHistoryModel];
        
        if (count == self.sleepArray.count)
        {  // 数据接收完成，上传服务器
            
            NSMutableString *datajsonString = [[NSMutableString alloc] initWithString:@"["];
            for (SleepHistoryModel *model in self.sleepArray) {
                NSString *string = [NSString stringWithFormat:@"{\"date\":\"20%@\",\"deep_sleep\":\"%@\",\"light_sleep\":\"%@\"},",model.startDate,[self handleSleepDataWithDh:model.Dh D1:model.D1],[self handleSleepDataWithDh:model.Lh D1:model.L1]];
                [datajsonString appendString:string];
            }
            NSUInteger location = [datajsonString length]-1;
            NSRange range = NSMakeRange(location, 1);
            [datajsonString replaceCharactersInRange:range withString:@"]"];
//            NSLog(@"睡眠历史：%@",self.sleepArray);
            NSLog(@"睡眠历史JSON：%@",datajsonString);
            [self.sleepArray removeAllObjects];
            UploadSleepDataApi *api = [[UploadSleepDataApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"data":datajsonString}];
            [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                NSDictionary *dict = [request responseJSONObject];
                if ([dict[@"errcode"] intValue] == 0)
                {
                    [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"手环睡眠数据上传成功")];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"手环睡眠数据上传失败")];
                }
            } failure:nil];
        }
        
        if (count < self.sleepArray.count) // 属于异常情况，清空数组
        {
            [self.sleepArray removeAllObjects];
        }
    }
}


#pragma mark ---- 辐射值处理 ------
- (void)handleRadiate:(NSString *)dataString
{
    NSString *code = dataString.subString(2,4); // OP
    switch ([code intValue]) {
        case 0:
        {
            if (self.radiateBlock)
            {
                NSString *V3 = dataString.subString(8,10);
                NSString *V2 = dataString.subString(10,12);
                NSString *V1 = dataString.subString(12,14);
                NSString *V0 = dataString.subString(14,16);
                float val = intlBitsToFloat((int)(([[NSString hexadecimalToDecimal:V3] intValue]<<24)|([[NSString hexadecimalToDecimal:V2] intValue]<<16)|([[NSString hexadecimalToDecimal:V1] intValue]<<8)|([[NSString hexadecimalToDecimal:V0] intValue]<<0)));
                self.radiateBlock([NSString stringWithFormat:@"%.2f",val]);
                [self settingTodayRadiation:val];
                NSLog(@"当前辐射值：%.2f",val);
            }
        }
            break;
        case 1:
        {

        }
            break;
        case 2:
        {
            
        }
            break;
            
        default:
            break;
    }
}

// 将辐射最大值上传服务器
- (void)settingTodayRadiation:(CGFloat)radiate
{
    if (radiate > self.radiateMax)
    {
        SetTodayRadiationApi *api = [[SetTodayRadiationApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"radiation":[NSString stringWithFormat:@"%.2f",radiate]}];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        } failure:nil];
        self.radiateMax = radiate;
    }
}

float intlBitsToFloat(int i)
{
    union
    {
        int i;
        float f;
    } u;
    u.i = i;
    return u.f;
}

#pragma mark ---- 电量值处理 ------
- (void)handleBattery:(NSString *)dataString
{
    NSString *code = dataString.subString(2,4);
    if ([code intValue] == 6)
    {
        NSString *battery = dataString.subString(16,18);
        self.battery = [NSString stringWithFormat:@"%i",[[NSString hexadecimalToDecimal:battery] intValue]/10];
        [[NSNotificationCenter defaultCenter] postNotificationName:BatteryState object:nil];
    }
}

#pragma mark ---- 运动值处理 ------
- (void)handleSportData:(NSString *)dataString
{
    NSString *code = dataString.subString(2,4);
    if ([code integerValue] == 7) // 当天步数上报
    {
        SportModel *model = [[SportModel alloc] initWithHexadecimalBackContent:dataString.fromIndex(4) propertyBytes:@[@"6",@"6",@"6"]];
        if (self.sportBlock)
        {
            self.sportBlock([NSString hexadecimalToDecimal:model.step], [NSString hexadecimalToDecimal:model.mileage], [NSString hexadecimalToDecimal:model.calorie]);
        }
    }
    else if ([code isEqualToString:@"C0"]) // 运动历史记录
    {
        [self handleSportHistory:dataString];
    }


}

- (void)handleSportHistory:(NSString *)dataString
{
//    NSInteger number = [dataString.subString(6,8) intValue];
    NSInteger count = [[NSString hexadecimalToDecimal:dataString.subString(4,6)] intValue];//总数

    if (count > 0)
    {
        SportHistoryModel *sportHistoryModel = [[SportHistoryModel alloc] initWithHexadecimalBackContent:dataString.fromIndex(8) propertyBytes:@[@"6",@"6",@"6",@"6"]];
        [self.sportArray addObject:sportHistoryModel];
        
        if (count == self.sportArray.count)
        {  // 数据接收完成，上传服务器
            
            NSMutableString *datajsonString = [[NSMutableString alloc] initWithString:@"["];
            for (SportHistoryModel *model in self.sportArray) {
                NSString *string = [NSString stringWithFormat:@"{\"date\":\"20%@\",\"step\":\"%@\",\"calorie\":\"%@\",\"distance\":\"%@\"},",model.date,model.step,model.calorie,model.distance];
                [datajsonString appendString:string];
            }
            NSUInteger location = [datajsonString length]-1;
            NSRange range = NSMakeRange(location, 1);
            [datajsonString replaceCharactersInRange:range withString:@"]"];
            NSLog(@"运动历史：%@",self.sportArray);
            NSLog(@"运动历史JSON：%@",datajsonString);
            [self.sportArray removeAllObjects];
            UploadSportDataApi *api = [[UploadSportDataApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"data":datajsonString}];
            [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                NSDictionary *dict = [request responseJSONObject];
                if ([dict[@"errcode"] intValue] == 0)
                {
                    [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"手环运动数据上传成功")];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"手环运动数据上传失败")];
                }
            } failure:nil];
        }
        
        if (count < self.sportArray.count) // 属于异常情况，清空数组
        {
            [self.sportArray removeAllObjects];
        }
    }
   
}


- (NSMutableArray *)sportArray
{
    if(!_sportArray)
    {
        _sportArray = [[NSMutableArray alloc]init];
    }
    return _sportArray;
}

- (NSMutableArray *)sleepArray
{
    if(!_sleepArray)
    {
        _sleepArray = [[NSMutableArray alloc]init];
    }
    return _sleepArray;
}


- (NSString *)battery
{
    if(!_battery)
    {
        _battery = @"0";
    }
    return _battery;
}

//- (void)getCurrentWeek:(void(^)(NSString *startTime,NSString *endTime))result{
//    
//    NSMutableArray *weekArr = [NSMutableArray array];
//    NSDate *currentDate = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSInteger week = [self getWeekDay:currentDate];
//    
//    for (NSInteger i = 1; i < 8; i++) {
//        NSDateComponents * components = [[NSDateComponents alloc] init];
//        components.year = 0;
//        components.day = i - week;
//        components.hour = 0;
//        
//        NSDate *nextDate = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
//        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyyMMdd";
//        NSString * str = [formatter stringFromDate:nextDate];
//        //        NSLog(@"%@",str);
//        [weekArr addObject:str];
//    }
//    //    NSLog(@"%@",weekArr);
//    result(weekArr.firstObject,weekArr.lastObject);
//}
//
//- (NSInteger)getWeekDay:(NSDate *)date
//{
//    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    
//    NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
//    NSInteger weekday = [comps weekday];
//    weekday--;
//    return weekday;
//}

- (NSArray *)getWeekWithIndex:(NSInteger)dateIndex
{
    NSDate *today = [NSDate date];
    NSTimeInterval secondsPerDay = 7 * 24 * 60 * 60 * dateIndex;
    NSDate *date = [today dateByAddingTimeInterval: secondsPerDay];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
    NSMutableArray *weekArr = [NSMutableArray array];
//    NSDate *currentDate = [NSDate date];
    //    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger week = [self getWeekDay:date];
    
//    NSInteger weekday = [dateComponents weekday];   //第几天(从sunday开始)
    for (NSInteger i = 1; i < 8; i++) {
        NSDateComponents * components = [[NSDateComponents alloc] init];
        components.year = 0;
        components.day = i - week;
        components.hour = 0;
        
        NSDate *nextDate = [calendar dateByAddingComponents:components toDate:date options:NSCalendarMatchStrictly];
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMdd";
        NSString * str = [formatter stringFromDate:nextDate];
//        NSLog(@"%@",str);
        [weekArr addObject:str];
    }
    return weekArr;
}

- (void)getCurrentWeekWithIndex:(NSInteger)dateIndex result:(void(^)(NSString *startTime,NSString *endTime,NSArray *weekArray))result
{
    NSDate *today = [NSDate date];
    NSTimeInterval secondsPerDay = 7 * 24 * 60 * 60 * dateIndex;
    NSDate *date = [today dateByAddingTimeInterval: secondsPerDay];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
    NSInteger weekday = [dateComponents weekday];   //第几天(从sunday开始)
    NSInteger firstDiff,lastDiff;
    if (weekday == 1) {
        firstDiff = -6;
        lastDiff = 0;
    }else {
        firstDiff =  - weekday + 2;
        lastDiff = 8 - weekday;
    }
    NSInteger day = [dateComponents day];
    NSDateComponents *firstComponents = [calendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
    [firstComponents setDay:day+firstDiff];
    NSDate *firstDay = [calendar dateFromComponents:firstComponents];
    
    NSDateComponents *lastComponents = [calendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
    [lastComponents setDay:day+lastDiff];
    NSDate *lastDay = [calendar dateFromComponents:lastComponents];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMdd";
    NSString * first = [formatter stringFromDate:firstDay];
    NSString * last = [formatter stringFromDate:lastDay];
    
    // 获取整个周的日期
    NSMutableArray *weekArr = [NSMutableArray array];
    NSDate *currentDate = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger week = [self getWeekDay:currentDate];
    
    for (NSInteger i = 1; i < 8; i++) {
        NSDateComponents * components = [[NSDateComponents alloc] init];
        components.year = 0;
        components.day = i - week;
        components.hour = 0;
        
        NSDate *nextDate = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMdd";
        NSString * str = [formatter stringFromDate:nextDate];
        NSLog(@"%@",str);
        [weekArr addObject:str];
    }
    //    NSLog(@"%@",weekArr);
    result(first,last,weekArr);
}

- (void)getCurrentMonthWithIndex:(NSInteger)dateIndex result:(void(^)(NSString *startTime,NSString *endTime))result
{
    NSDate *today = [NSDate date];
    NSTimeInterval secondsPerDay = 30 * 24 * 60 * 60 * dateIndex;
    NSDate *date = [today dateByAddingTimeInterval: secondsPerDay];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *firstDay;
    [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&firstDay interval:nil forDate:date];
    NSDateComponents *lastDateComponents = [calendar components:NSMonthCalendarUnit | NSYearCalendarUnit |NSDayCalendarUnit fromDate:firstDay];
    NSUInteger dayNumberOfMonth = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date].length;
    NSInteger day = [lastDateComponents day];
    [lastDateComponents setDay:day+dayNumberOfMonth-1];
    NSDate *lastDay = [calendar dateFromComponents:lastDateComponents];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMdd";
    NSString * first = [formatter stringFromDate:firstDay];
    NSString * last = [formatter stringFromDate:lastDay];
    
    result(first,last);
}



- (NSArray *)getMonthWithIndex:(NSInteger)dateIndex
{
    NSDate *today = [NSDate date];
    NSTimeInterval secondsPerDay = 30 * 24 * 60 * 60 * dateIndex;
    NSDate *date = [today dateByAddingTimeInterval: secondsPerDay];
    
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMM";
    NSString * str = [formatter stringFromDate:date];
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 1; i <= range.length; i++)
    {
        NSString *last = [NSString stringWithFormat:@"%@%02d",str,i];
        NSLog(@"%@",last);
        [array addObject:last];
    }
    return array;
//    NSString *first = [NSString stringWithFormat:@"%@.01",str];
//    NSString *last = [NSString stringWithFormat:@"%@.%zd",str,range.length];
//    NSLog(@"%@,%@",first,last);
//    return @[first,last];
    
}


- (NSInteger)getWeekDay:(NSDate *)date
{
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
    NSInteger weekday = [comps weekday];
    weekday--;
    return weekday;
}
//- (void)getCurrentMonth:(void(^)(NSString *startTime,NSString *endTime))result{
//    
//    NSMutableArray *weekArr = [NSMutableArray array];
//    NSDate *currentDate = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSInteger week = [self getMonthDay:currentDate];
//    
//    for (NSInteger i = 1; i < 8; i++) {
//        NSDateComponents * components = [[NSDateComponents alloc] init];
//        components.year = 0;
//        
//        components.day = i - week;
//        components.hour = 0;
//        
//        NSDate *nextDate = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
//        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyyMMdd";
//        NSString * str = [formatter stringFromDate:nextDate];
//        //        NSLog(@"%@",str);
//        [weekArr addObject:str];
//    }
//    //    NSLog(@"%@",weekArr);
//    result(weekArr.firstObject,weekArr.lastObject);
//}
//
//- (NSInteger)getMonthDay:(NSDate *)date
//{
//    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    
//    NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
//    NSInteger weekday = [comps month];
//    weekday--;
//    return weekday;
//}
//
//// 当前月第一天
//- (void)firstDay
//{
//    NSDate *now = [NSDate date];
//    NSCalendar *cal = [NSCalendar currentCalendar];
//    NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:now];
//    comps.day = 1;
//    NSDate *firstDay = [cal dateFromComponents:comps];
//    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//    formatter.dateFormat = @"yyyyMMdd";
//    NSString * str = [formatter stringFromDate:firstDay];
//}

//float byte2float(Byte byte[],int index)
//{
//    int l;
//    l = byte[index + 0];
//    l &= 0xff;
//    l |= ((long) byte[index + 1] << 8);
//    l &= 0xFFFF;
//    l |= ((long) byte[index + 2] << 16);
//    l &= 0xFFFFFF;
//    l |= ((long) byte[index + 3] << 24);
//    return intlBitsToFloat(l);
//}

@end
